package de.mrclrchtr.education.account.service

import de.mrclrchtr.education.account.dto.RoleDto
import de.mrclrchtr.education.account.jooq.tables.references.ROLE
import de.mrclrchtr.education.account.jooq.tables.pojos.Role
import de.mrclrchtr.education.account.jooq.tables.pojos.User
import de.mrclrchtr.education.account.jooq.tables.references.ROLE_USER
import org.jooq.DSLContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class RoleService(
    @Autowired private val dslContext: DSLContext,
    @Lazy @Autowired private val userService: UserService
) {
    /**
     * 获取所有的角色
     */
    fun getAllRoles(): MutableList<RoleDto> {
        val mutableList = mutableListOf<RoleDto>()
        val roleMap = mutableMapOf<Role, RoleDto>()
        try {
            dslContext.select().from(ROLE)
                .leftJoin(ROLE_USER).on(ROLE.ID.eq(ROLE_USER.ROLE_ID))
                .fetch().forEach {
                    var userList: MutableList<User> = mutableListOf()
                    if (it.getValue(ROLE_USER.USER_ID) != null) {
                        userList = userService.getUsersById(it.getValue(ROLE_USER.USER_ID))
                    }
                    val roleId = it.getValue(ROLE.ID)
                    val roleName = it.getValue(ROLE.NAME)
                    val role = Role(roleId, roleName)

                    if (roleMap.containsKey(role)) {
                        roleMap[role]?.userList?.addAll(userList)
                    } else {
                        roleMap[role] = RoleDto.convertToCustomRole(role, userList)
                    }
                }
            // 将结果从map转换回list
            mutableList.addAll(roleMap.values)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mutableList
    }

    /**
     * 根据id获取角色
     */
    fun getRoleByIdWithUsers(id: Int?): RoleDto? {
        return try {
            val roleRecord = dslContext.selectFrom(ROLE)
                .where(ROLE.ID.eq(id))
                .fetchOne()

            roleRecord?.let { role ->
                val roleId = role[ROLE.ID]
                val roleName = role[ROLE.NAME]

                // 查询与该角色关联的所有用户ID
                val userRoleRecords = dslContext.select(ROLE_USER.USER_ID)
                    .from(ROLE_USER)
                    .where(ROLE_USER.ROLE_ID.eq(roleId))
                    .fetch()

                // 根据用户ID获取用户列表
                val userList = userRoleRecords.mapNotNull { userService.getUsersById(it[ROLE_USER.USER_ID]) }.flatten()
                    .toMutableList()
                // 封装RoleDto
                RoleDto.convertToCustomRole(Role(roleId, roleName), userList)
            }
        } catch (e: Exception) {
            // 日志记录异常，或者其他异常处理逻辑
            e.printStackTrace()
            null
        }
    }


    /***
     * 获取角色的信息为集合返回
     */
    fun getRolesById(id: Int?): MutableList<Role> {
        var mutableList = MutableList(0) { Role(0, "") }
        dslContext.select().from(ROLE).where(ROLE.ID.eq(id)).fetch().forEach {
            mutableList.add(Role(it.getValue(ROLE.ID), it.getValue(ROLE.NAME)))
        }
        return mutableList
    }


    /**
     * 修改角色,基础信息加上更新的userid
     */
    fun updateRole(role: Role, userIds: List<Int>): String {
        if (role.id == null || userIds.isEmpty()) {
            return "无效的参数，无法更新"
        }
        // 更新角色名称
        dslContext.update(ROLE).set(ROLE.NAME, role.name).where(ROLE.ID.eq(role.id)).execute()

        // 获取当前角色关联的用户ID
        val existingUserIds = dslContext.select(ROLE_USER.USER_ID).from(ROLE_USER).where(ROLE_USER.ROLE_ID.eq(role.id))
            .fetchInto(Int::class.java)

        // 计算需要删除的用户ID
        val toDeleteUserIds = existingUserIds.minus(userIds)
        // 删除不再关联的用户
        if (toDeleteUserIds.isNotEmpty()) {
            dslContext.deleteFrom(ROLE_USER).where(ROLE_USER.ROLE_ID.eq(role.id))
                .and(ROLE_USER.USER_ID.`in`(toDeleteUserIds)).execute()
        }

        // 计算需要插入的用户ID
        val toInsertUserIds = userIds.minus(existingUserIds)
        // 插入新的用户关系
        if (toInsertUserIds.isNotEmpty()) {
            toInsertUserIds.forEach { userId ->
                dslContext.insertInto(ROLE_USER)
                    .columns(ROLE_USER.ROLE_ID, ROLE_USER.USER_ID)
                    .values(role.id, userId)
                    .execute()
            }
        }
        return "更新成功"
    }


    /**
     * 根据id删除角色
     */
    fun deleteRoleById(id: Int?): String {
        if (id == null) {
            return "无效的参数，无法删除"
        }
        // 删除角色
        dslContext.deleteFrom(ROLE).where(ROLE.ID.eq(id)).execute()
        // 删除角色关联的用户
        dslContext.deleteFrom(ROLE_USER).where(ROLE_USER.ROLE_ID.eq(id)).execute()
        return "删除成功"
    }

    /**
     * 新增角色
     */
    fun addRole(role: Role): String {
        if (role.id == null) {
            return "无效的参数，无法新增"
        }
        val execute = dslContext.insertInto(ROLE).set(ROLE.NAME, role.name).execute()
        if (execute > 0) return "新增成功" else return "新增失败"
    }
}

